namespace Team.API.Services
{
    /// <summary>
    /// 设备状态后台服务
    /// 每分钟检查并更新设备状态
    /// </summary>
    public class EquipmentStatusBackgroundService : BackgroundService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<EquipmentStatusBackgroundService> _logger;
        private readonly TimeSpan _interval = TimeSpan.FromMinutes(1); // 每分钟执行一次

        public EquipmentStatusBackgroundService(
            IServiceProvider serviceProvider,
            ILogger<EquipmentStatusBackgroundService> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("设备状态后台服务已启动");

            // 延迟5秒后开始执行，避免启动时立即执行
            await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    using var scope = _serviceProvider.CreateScope();
                    var equipmentStatusService = scope.ServiceProvider.GetRequiredService<IEquipmentStatusService>();
                    
                    var (updatedCount, equipmentNames) = await equipmentStatusService.CheckAndUpdateEquipmentStatusAsync(
                        "定时任务",
                        stoppingToken);

                    if (updatedCount > 0)
                    {
                        _logger.LogInformation($"定时任务完成：更新了 {updatedCount} 个设备状态");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "检查设备状态时发生错误");
                }

                // 等待1分钟后再次执行
                await Task.Delay(_interval, stoppingToken);
            }

            _logger.LogInformation("设备状态后台服务已停止");
        }
    }
}
